import { useState } from "react"

function Square({ value, onSquareClick }: { value: string, onSquareClick: () => void }) {
  return <button className="square" onClick={onSquareClick}>{value}</button>
}
function Board({ squares, nextIsX, onPlay }:
  {
    squares: string[],
    nextIsX: boolean,
    onPlay: ({ nextSquares }: { nextSquares: string[] }) => void
  }
) {
  function handleClick(i: number) {
    if (squares[i] || calculateWinner(squares)) {
      console.log("square is already filled or there is a winner")
      return
    }
    const nextSquares = squares.slice()
    if (nextIsX) {
      nextSquares[i] = 'X'
    } else {
      nextSquares[i] = 'O'
    }
    onPlay({ nextSquares })
  }
  const winner = calculateWinner(squares)
  return (
    <>
      <div className="status">
        {winner ? `Winner: ${winner}` : `Next player: ${nextIsX ? 'X' : 'O'}`}
      </div>
      <div className="board-row">
        <Square value={squares[0]} onSquareClick={() => handleClick(0)} />
        <Square value={squares[1]} onSquareClick={() => handleClick(1)} />
        <Square value={squares[2]} onSquareClick={() => handleClick(2)} />
      </div>
      <div className="board-row">
        <Square value={squares[3]} onSquareClick={() => handleClick(3)} />
        <Square value={squares[4]} onSquareClick={() => handleClick(4)} />
        <Square value={squares[5]} onSquareClick={() => handleClick(5)} />
      </div>
      <div className="board-row">
        <Square value={squares[6]} onSquareClick={() => handleClick(6)} />
        <Square value={squares[7]} onSquareClick={() => handleClick(7)} />
        <Square value={squares[8]} onSquareClick={() => handleClick(8)} />
      </div>
    </>
  )
}

export default function Game() {
  const [history, setHistory] = useState([Array(9).fill(null)])
  const [currentMove, setCurrentMove] = useState(0)
  const xIsNext = currentMove % 2 === 0
  const currentSquare = history[currentMove]
  function onPlay({ nextSquares }: { nextSquares: string[] }) {
    const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]
    setHistory(nextHistory)
    setCurrentMove(nextHistory.length - 1)
  }

  function jumpTo(step: number) {
    setCurrentMove(step)
  }

  const moves = history.map((square, i) => {
    if (!square) {
      return
    }
    return (
      <li key={i}>
        <button onClick={() => jumpTo(i)}>
          {i === 0 ? 'Go to game start' : `Go to move #${i}`}
        </button>
      </li>
    )
  })

  return (
    <div className="game">
      <div className="game-board">
        <Board squares={currentSquare} nextIsX={xIsNext} onPlay={onPlay} />
      </div>
      <div className="game-info">
        <ol>{moves}</ol>
      </div>
    </div>
  )
}

function calculateWinner(squares: string[]) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ]
  for (const [a, b, c] of lines) {
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a]
    }
  }
  return null
}